const fs = require('fs-extra');
const path = require('path')
const package = require('./package.json')
var JavaScriptObfuscator = require('javascript-obfuscator')

// 清空文件夹
fs.emptyDirSync(path.join(__dirname, 'dist'))
fs.emptyDirSync(path.join(__dirname, 'build'))

package.main = 'index.js'
package.scripts.build = package.scripts.build_s

package.devDependencies = {"electron": "file:../node_modules/electron"}

fs.writeJSONSync(path.join(__dirname, 'build/package.json'), package)

let srcPath = path.join(__dirname, 'src');

(function _iter(pathname) {
  let stat = fs.statSync(pathname)
  if (stat.isDirectory()) {
    let dirs = fs.readdirSync(pathname)
    dirs.forEach(item => {
      _iter(path.join(pathname, item))
    })
  } else {
    let name = path.join(__dirname, './build', pathname.replace(path.join(__dirname, 'src'), ''))
    // fs.mkdirpSync()
    let exist = fs.existsSync(path.dirname(name))
    if (!exist) fs.mkdirpSync(path.dirname(name))

    let code = fs.readFileSync(pathname)
    code = code.toString()
    console.log('BUILD: ', name)
    if (path.extname(name) == '.js') {
      var obfuscationResult = JavaScriptObfuscator.obfuscate(code, {
        compact: true, controlFlowFlattening: true
      })
      fs.writeFileSync(name, obfuscationResult.getObfuscatedCode())
    } else {
      fs.copyFileSync(pathname, name)
    }
  }
})(srcPath)


let child = require('child_process').spawn('npm', ['run', 'build'], {
  cwd: path.join(__dirname, 'build'), shell: true
})

child.stdout.on('data', (data) => {
  console.log(`${data.toString()}`);
});

child.stderr.on('data', (data) => {
  console.error(`${data.toString()}`);
});

child.on('close', (code) => {
  fs.removeSync(path.join(__dirname, 'build'))
  let dir = fs.readdirSync(path.join(__dirname, 'dist'))
  fs.copySync(path.join(__dirname, 'miniblink'), path.join(__dirname, 'dist/miniblink'))
  fs.copySync(path.join(__dirname, 'dist', dir[0], 'resources'), path.join(__dirname, 'dist/miniblink/resources'))
  fs.removeSync(path.join(__dirname, 'dist', dir[0]))

  console.log('complete !!!')
});